package nettyhttpserver;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.cookie.CookieEncoder;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
import io.netty.handler.codec.http.multipart.MemoryAttribute;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;
/**
 * 用来解析请求参数
 * 
 * @author 阿友 3798955@qq.com
 *
 */
public class HttpTestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
//extends ChannelInboundHandlerAdapter{
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
		System.out.println("----------打印开始----------\r\n");
		System.out.println("\r\n\r\n请求地址:  " + msg.uri());
		System.out.println("请求头文件----------1--------\r\n ");
		HttpHeaders hh = msg.headers();
		hh.forEach((v) -> {
			System.out.println(v);
		});
		System.out.println("请求头文件---------end--------\r\n");
		System.out.println("GET参数---------2---------\r\n");
		Map<String, String> li = getGetParams(ctx, msg);
		for (String key : li.keySet()) {
			System.out.println(key + "=" + li.get(key));
		}
		System.out.println("GET参数----------end--------\r\n");
		System.out.println("POST参数----------3----------\r\n");
		li = getPostParams(ctx, msg);
		for (String key : li.keySet()) {
			System.out.println(key + "=" + li.get(key));
		}
		System.out.println("POST参数----------end----------\r\n");
		channelRead1(ctx, msg);
		channelRead2(ctx, msg);
		System.out.println("----------打印结束----------\r\n");
	}
	private Map<String, String> getGetParams(ChannelHandlerContext ctx, HttpRequest req) {
		Map<String, String> requestParams = new HashMap<>();
		// 处理get请求
		if (req.method() == HttpMethod.GET) {
			QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
			Map<String, List<String>> parame = decoder.parameters();
			Iterator<Entry<String, List<String>>> iterator = parame.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, List<String>> next = iterator.next();
				requestParams.put(next.getKey(), next.getValue().get(0));
			}
		}
		return requestParams;
	}
	private Map<String, String> getPostParams(ChannelHandlerContext ctx, HttpRequest req) {
		Map<String, String> requestParams = new HashMap<>();
		// 处理POST请求
		if (req.method() == HttpMethod.POST) {
			HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);
			List<InterfaceHttpData> postData = decoder.getBodyHttpDatas(); //
			for (InterfaceHttpData data : postData) {
				if (data.getHttpDataType() == HttpDataType.Attribute) {
					MemoryAttribute attribute = (MemoryAttribute) data;
					requestParams.put(attribute.getName(), attribute.getValue());
				}
			}
		}
		return requestParams;
	}
	protected void channelRead1(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

		ByteBuf jsonBuf = request.content();
		String jsonStr = jsonBuf.toString(CharsetUtil.UTF_8);
		System.out.println("请求内容-------4---------\r\n");
		System.out.println(jsonStr);
		System.out.println("请求内容-------end---------\r\n");
	}
	private AsciiString contentType = HttpHeaderValues.TEXT_PLAIN;
	protected void channelRead2(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
		System.out.println("端口响应-------5-------\r\n");
		System.out.println("类名:" + msg.getClass().getName());
		DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
				Unpooled.wrappedBuffer("ok".getBytes())); // 2
		HttpHeaders heads = response.headers();
		heads.add(HttpHeaderNames.CONTENT_TYPE, contentType + "; charset=UTF-8");
		heads.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // 3
		heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
		ctx.write(response);
		System.out.println("端口响应-------end-------\r\n");
	}
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// System.out.println("server channelReadComplete..");
		 ctx.flush();//刷新后才将数据发出到SocketChannel
	}
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println("server exceptionCaught..");
		ctx.close();
	}
}
